#include "jsonutils.h"

JsonUtils::JsonUtils()
{

}

void JsonUtils::readJsonFile(QString filePath,bool isParentData, QList<ItemModel> &items)
{
    QFile loadFile(filePath);
    if(!loadFile.open(QIODevice::ReadOnly))
    {
        qDebug() << "could't open projects json";
        return;
    }

    QByteArray allData = loadFile.readAll();
    loadFile.close();

    QJsonParseError json_error;
    QJsonDocument jsonDoc(QJsonDocument::fromJson(allData, &json_error));

    if(json_error.error != QJsonParseError::NoError)
    {
        qDebug() << "json error!";
        return;
    }

    QJsonObject rootObj = jsonDoc.object();

    QStringList keys = rootObj.keys();

    //因为是预先定义好的JSON数据格式，所以这里可以这样读取
    if(rootObj.contains("data"))
    {
       QJsonArray dataArray = rootObj.value("data").toArray();
       if (isParentData){
            dataArray =  rootObj.value("data").toObject().value("parents").toArray();
       } else {
            dataArray =  rootObj.value("data").toObject().value("subclass").toArray();
       }

       for(int i = 0; i< dataArray.size(); i++)
       {
           QJsonObject subObj = dataArray.at(i).toObject();
           ItemModel item;
           item.id = subObj.value("id").toString();
           item.name = subObj.value("actionName").toString();
           item.code = subObj.value("actionCode").toString();
           if(subObj.contains("parentId")){
                item.parentId = subObj.value("parentId").toString();
           } else {
                item.parentId = nullptr;
           }
           item.isEnable = subObj.value("isEnabled").toBool();
           items.append(item);
       }
    }
}
